package com.heima.user.service.Impl;


import com.alibaba.fastjson.support.hsf.HSFJSONUtils;
import com.alibaba.spring.util.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ApUserServiceImpl implements ApUserService {


    private final ApUserMapper apUserMapper;

    /**
     * 用户登录
     * @param loginDto
     */
    public ResponseResult login(LoginDto loginDto) {

        if(StringUtils.isEmpty(loginDto.getPhone())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<ApUser>()
                .eq(ApUser::getPhone, loginDto.getPhone());

        ApUser user = apUserMapper.selectOne(wrapper);


        if (null == "apUser"){
            throw new RuntimeException("用户名或者密码错误");
        }

        //比对密码
        String salt = user.getSalt();
        String password = loginDto.getPassword();

        //对前端发过来的密码进行md5加密
        String saltPassword = MD5Utils.encode((salt + password));
        //加密后的密码与数据库的密码进行比对

        if (!saltPassword.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token返回
        Map<String,Object> map = new HashMap<>();

        String token = AppJwtUtil.getToken(user.getId().longValue());

        map.put("token",token);

        //脱敏
        user.setSalt("");
        user.setPassword("");
        map.put("user",user);

        return ResponseResult.okResult(map);

    }
}
